package com.example.charactivity.ChartDaily

import android.app.usage.UsageStatsManager
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ScrollView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.charactivity.*
import com.example.charactivity.ChartDaily.DayChartViewModel.daily.appinfo
import com.example.recyclerview.viewHolder.ViewAdapter
import com.example.remindme.R
import com.github.aachartmodel.aainfographics.aachartcreator.AAChartView

import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*
import kotlin.concurrent.thread

class DayChartFragment : Fragment() {
    private val usageStatics by lazy {
        UsageStatics()
    }
    private val myChartModel by lazy {
        GernerChartModel()
    }

    private lateinit var   aaChartView: AAChartView

    companion object {
        fun newInstance() = DayChartFragment()
    }

    private lateinit var viewModel: DayChartViewModel
    lateinit var lastBtn:Button
    lateinit var nxtBtn:Button

    lateinit var dayRecycler: RecyclerView
    lateinit var getTop:Button
    lateinit var dayScrollView: ScrollView
    lateinit var now:Calendar


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
// 权限判断

// 打开应用会进行查询，

    }
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // 设置当前fragment的文档
        return inflater.inflate(R.layout.day_chart_fragment, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProvider(this).get(DayChartViewModel::class.java)
         now=Calendar.getInstance()
        viewModel.nowTime= Calendar.getInstance()
// 默认是引用！

       val v=getView()
        if(v!=null)
        {
            aaChartView = v.findViewById(R.id.week_chart_view)
            lastBtn=v.findViewById(R.id.lastd)
            nxtBtn=v.findViewById(R.id.nextd)
           dayRecycler=v.findViewById<RecyclerView>(R.id.day_recycler)
            getTop=v.findViewById(R.id.gotop)
            dayScrollView=v.findViewById(R.id.dayScro)

        }
        aaChartView.aa_drawChartWithChartModel(GernerChartModel.aaChartModel)

        viewModel.millisTime.observe(this,{
           DayChartViewModel.configureChart()
            aaChartView.aa_drawChartWithChartModel(GernerChartModel.aaChartModel)
        }
        )


        nxtBtn.isEnabled=false
        dayRecycler.layoutManager= LinearLayoutManager(activity)
        initButton()
        getInformation()
        // 更新信息以后，再去更新ui
        configurRecycler()


    }



    private fun configurRecycler() {
        val adapter= ViewAdapter(DayChartViewModel.appinfo)  // adapeter 会在内部完成
        dayRecycler.adapter=adapter
    }

    private fun initButton() {
        lastBtn.setOnClickListener{

            dayScrollView.smoothScrollTo(0,0)
            //  val format: DateFormat = SimpleDateFormat("yyyy.MM.dd：HH:MM:ss", Locale.getDefault())
            // Log.i("time",format.format(Date(viewModel.nowTime.timeInMillis)))
            // Log.i("time",format.format(Date(now.timeInMillis)))
            viewModel.nowTime.add(Calendar.DAY_OF_YEAR,-1)
            getInformation()
            configurRecycler()
            nxtBtn.isEnabled = viewModel.nowTime < now
        }
        nxtBtn.setOnClickListener{
            dayScrollView.smoothScrollTo(0,0)
            viewModel.nowTime.add(Calendar.DAY_OF_YEAR,1)
            getInformation()
            configurRecycler()
            nxtBtn.isEnabled = viewModel.nowTime < now
        }
        getTop.setOnClickListener{
            dayScrollView.smoothScrollTo(0,0)
        }

    }

    fun getInformation()
    {

        val cycleInterval=1000*60*60*24*1
        val endTime = viewModel.nowTime.timeInMillis
        val beginTime= endTime-cycleInterval
        val format: DateFormat = SimpleDateFormat("yyyy.MM.dd", Locale.getDefault())
        val beginStr:String=format.format(Date(beginTime))
        val endStr:String=format.format(Date(endTime))
        // 修改标题
        GernerChartModel.aaChartModel.title("$beginStr—$endStr")

// 在frgment里面利用activity获取当前的activity
        val usageStateManager= activity!!.getSystemService(AppCompatActivity.USAGE_STATS_SERVICE) as UsageStatsManager
        val usageStatsList =usageStateManager .queryUsageStats(UsageStatsManager.INTERVAL_DAILY, beginTime, endTime)
        thread {
            viewModel.millisTime.postValue(viewModel.sortData(usageStatsList))
        }

        // 显示查询到的信息

        // 这里面修改了viemodel的值，检测到变化，会立即更新的

// 得到每两个小时计数一次的内容数组，即12*5


        // 通过sevice获取
        /*
        val usageEventStats=usageStateManager.queryEventStats(UsageStatsManager.INTERVAL_BEST,beginTime,endTime) as List<EventStats>
        val envets=usageStateManager.queryEvents(beginTime,endTime)
        var kuqi:Set<UsageEvents>
      //  var lo=envets.getNextEvent(UsageEvents.Event())
        // 没有完工哦！
       // var leimu=
        while(envets.hasNextEvent())
        {
            val format=SimpleDateFormat("yyyy.MM.dd_HH:mm:ss",Locale.getDefault())
            var tem=UsageEvents.Event()
            envets.getNextEvent(tem)


            var name=tem.packageName
            var start=0L
            var back=0L

         //   Log.i("event", "|$name：|${format.format(Date(start))}——${format.format(Date(back))}|${back-start}")
            Log.i("event",
                "|$name---|${format.format(Date(tem.timeStamp))}|${tem.eventType}|${back-start}")

            if(tem.eventType==1)
                start= tem.timeStamp
            if(tem.eventType==2) {
                back = tem.timeStamp
                Log.i("event",
                "|$name---|${format.format(Date(start))}===${format.format(Date(back))}|${back-start}")
                start=0
                back=0
            }



        }*/


    }

}